package com.example.orderservice.listener;


import com.example.orderservice.constants.MQConstants;
import com.example.orderservice.domain.entity.Order;
import com.example.orderservice.service.IOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;


/**
 * 订单延迟消息监听器
 * 处理订单超时未支付的自动取消逻辑
 *
 * @author czwa
 */
@Component
@RequiredArgsConstructor
public class OrderDelayMessageListener {

    private final IOrderService orderService;

    /**
     * 监听订单延迟队列，处理超时未支付订单
     *
     * @param orderId 订单ID
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MQConstants.DELAY_ORDER_QUEUE_NAME),
            exchange = @Exchange(name = MQConstants.DELAY_EXCHANGE_NAME, delayed = "true"),
            key = MQConstants.DELAY_ORDER_KEY
    ))
    public void listenOrderDelayMessage(Long orderId) {
        // 1. 查询订单信息
        Order order = orderService.getById(orderId);

        // 2. 检查订单状态，执行相应操作
        if (order == null || order.getStatus() == 1) {
            // 订单不存在或已支付，无需处理
            return;
        } else if (order.getStatus() == 0) {
            // 订单未支付，执行自动取消逻辑
            orderService.cancelPay(orderId.intValue());
        }
    }
}